interface IData {
  value: number | string
  canichange: boolean
  selected: boolean
}

// 数独验证方法
export function verifySudoku(dataSource: Array<IData[]>): boolean {
  const data: Array<number[]> = dataSource.map((v) =>
    v.map((n) => n.value as number)
  )
  return verifyBox(data) && verifyRow(data) && verifyColumn(data)
}
// 验证行
function verifyRow(data: Array<number[]>): boolean {
  for (let i = 0; i < 9; i += 3) {
    for (let j = 0; j < 3; j++) {
      if (
        9 !==
        ArrayDedup([
          ...data[i].slice(j * 3, j * 3 + 3),
          ...data[i + 1].slice(j * 3, j * 3 + 3),
          ...data[i + 2].slice(j * 3, j * 3 + 3),
        ]).length
      ) {
        return false
      }
    }
  }
  return true
}

// 验证列
function verifyColumn(data: Array<number[]>): boolean {
  for (let i = 0; i < 9; i += 3) {
    for (let j = 0; j < 3; j++) {
      let arr = [
        data[i][j],
        data[i][j + 3],
        data[i][j + 6],
        data[i + 3][j],
        data[i + 3][j + 3],
        data[i + 3][j + 6],
        data[i + 6][j],
        data[i + 6][j + 3],
        data[i + 6][j + 6],
      ]
      if(9 !== ArrayDedup(arr).length) {
        return false
      }
    }
  }
  return true
}

// 验证每个小格子
function verifyBox(data: Array<number[]>): boolean {
  for (let i = 0; i < data.length; i++) {
    if (9 !== ArrayDedup(data[i]).length) {
      return false
    }
  }
  return true
}

// 数组去重
function ArrayDedup<T>(arr: T[]): T[] {
  const newArr: T[] = []
  arr.forEach((val) => {
    newArr.includes(val) ? '' : newArr.push(val)
  })
  return newArr
}
